﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    UserManagerViewModel
// 创建者：      杨程
// 创建日期：	    2022/12/17 16:25:28

//----------------------------------------------------------------*/

#endregion

using System.Linq.Expressions;

namespace Vampirewal.Admin.Server.ViewModels.ViewModel.OrganizationManager;

/// <summary>
///
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.UserManagerViewModel)]
public partial class UserManagerViewModel : BillListBaseVM<Sys_User, Sys_User>
{
    private SqlSugarRepository<Sys_Org> repOrg { get; set; }

    /// <summary>
    ///
    /// </summary>
    public UserManagerViewModel(IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_Org> _repOrg, SqlSugarRepository<Sys_User> _repUser, SqlSugarRepository<Sys_User> _repSearch) : base(dialog, _repUser, _repSearch)
    {
        repOrg = _repOrg;
        //构造函数

        OrgList.LoadFullNodes(_repOrg.ToList());

        TreeListViewActionsCommand = new IVampirewalCoreEventCommand[]
        {
            new VampirewalCoreEventCommand("SelectedItemChanged","SelectedItem", new RelayCommand<GeneralTreeContainer<Sys_Org>>(Selected =>
            {
                var org = Selected.TreeNode;

            if (org.OrgType != 0)
            {
                //Queryable = RepBill.AsQueryable().Where(w => w.DepartmentId == org.BillId);

                GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
            }
            }))
        };

        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }


    #region [     重写     ]

    protected override void InitVM()
    {
        OrgList = new TreeBuilderByFullLoad<Sys_Org>();
    }

    protected override IUcViewBase SetView()
    {
        switch (ViewKey)
        {
            case ServerViewKeys.EditUserView:
                return WindowsManager.GetInstance().GetView(ViewKey);

            default:
                throw new NotImplementedException();
        }
    }

    public override void ExecuteBeforeCloseDialogWindow(object obj)
    {
        //OrgList.LoadFullNodes(repOrg.ToList());
    }

    //protected override void GetList(bool IsUseGetSearchQuery, bool UsePageQuery = false)
    //{
    //    base.GetList(IsUseGetSearchQuery, UsePageQuery);


    //}

    protected override void GetPageList(Expression<Func<Sys_User, bool>> expression, Expression<Func<Sys_User, object>> order, OrderByType type = OrderByType.Asc, bool UsePage = true)
    {
        base.GetPageList(expression, order, type, UsePage);
    }

    #endregion

    #region [     属性     ]

    /// <summary>
    /// 底部页面
    /// </summary>
    [ObservableProperty]
    public IUcViewBase bottomContext;

    public TreeBuilderByFullLoad<Sys_Org> OrgList { get; set; }

    public IVampirewalCoreEventCommand[] TreeListViewActionsCommand { get; set; }

    private string ViewKey;

    #endregion

    #region [     Command命令     ]

    #region [     分页命令     ]

    /// <summary>
    ///     页码改变命令
    /// </summary>
    public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd =>
        new Lazy<RelayCommand<FunctionEventArgs<int>>>(() =>
            new RelayCommand<FunctionEventArgs<int>>(PageUpdated)).Value;

    /// <summary>
    ///     页码改变
    /// </summary>
    private void PageUpdated(FunctionEventArgs<int>? info)
    {
        

        EntityList.Clear();

        Page = info.Info;

        //GetList(Queryable == null ? true : false, true);
        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #endregion

    [RelayCommand]
    public void LookDetail(Sys_User user)
    {
        BottomContext = WindowsManager.GetInstance().GetView(ServerViewKeys.EditUserView, Param: user);
    }

    #endregion
}

[VampirewalIoCRegister(ServerViewModelKeys.EditUserViewModel)]
public partial class EditUserViewModel : BillVM<Sys_User>
{
    private SqlSugarRepository<Sys_User> repUser { get; set; }
    private IVampirewalCoreDialogMessage Dialog { get; set; }

    public EditUserViewModel(IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_User> _repUser) : base(_repUser)
    {
        repUser = _repUser;
        Dialog = dialog;
    }

    public override void PassData(object obj)
    {
        if (obj == null)
        {
            //新增
            Title = "新增租户";
        }
        else if (obj is Sys_User user)
        {
            Title = $"修改 {user.Name} ";
            SetEntity(user);
        }
        else
        {
            CloseView(); ;
        }
    }

    protected override void CloseView()
    {
        WindowsManager.GetInstance().CloseDialogWindow(ViewId);
    }

    [RelayCommand]
    public void Save()
    {
        //Dialog.ShowPopupWindow($"当前功能服务端仅作展示！具体业务请放到RPCService中！", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
        Dialog.ShowPopupWindow(new PopupWindowSetting()
        {
            Message= $"当前功能服务端仅作展示！具体业务请放到RPCService中！",
            OwnerWindow= WindowsManager.GetInstance().GetDialogWindow(ViewId),
            Type= MessageType.Error
        });
        return;

        List<Sys_User> OtherUser = new List<Sys_User>();

        if (Entity.IsCurrentDeptLeader)
        {
            var CurUser = repUser.FirstOrDefault(f => f.DepartmentId == Entity.DepartmentId && f.IsCurrentDeptLeader);

            if (CurUser != null)
            {
                //说明部门已经设置过一个负责人了
                //Dialog.ShowPopupWindow($"当前部门已经存在一位负责人，请先将该部门负责人撤下！", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
                return;
            }
            else
            {
                repUser.ToList(f => f.DepartmentId == Entity.DepartmentId && f.BillId != Entity.BillId).ForEach(f =>
                {
                    f.DirectLeaderId = Entity.BillId;
                });
            }
        }

        try
        {
            repUser.BeginTran();

            repUser.CommitTran();

            //if (ViewId == Guid.Empty)
            //    Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().MainWindow, MessageType.Successful);
            //else
            //    Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Successful);
        }
        catch (Exception ex)
        {
            repUser.RollbackTran();
            //if (ViewId == Guid.Empty)
            //    Dialog.ShowPopupWindow($"保存失败！:{ex.Message}", WindowsManager.GetInstance().MainWindow, MessageType.Error);
            //else
            //    Dialog.ShowPopupWindow($"保存失败！:{ex.Message}", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
        }
    }
}